#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :forms.py
# @Time      :2025/2/20 18:02
# @Author    :kk
from django import forms
from django.core.cache import cache

from app01.models import User


class RegisterForm(forms.Form):

    email = forms.EmailField()
    captcha = forms.CharField(min_length=4, max_length=4)
    username = forms.CharField(max_length=20, min_length=3)
    password = forms.CharField(max_length=20, min_length=6, widget=forms.PasswordInput)
    password_confirm = forms.CharField(max_length=20, min_length=6, widget=forms.PasswordInput)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        filter_result = User.objects.filter(email=email)
        if len(filter_result) > 0:
            raise forms.ValidationError("该邮箱已经被注册过了")

        return email

    def clean_username(self):
        username = self.cleaned_data.get('username')
        filter_result = User.objects.filter(username=username)
        if len(filter_result) > 0:
            raise forms.ValidationError("该用户名已经被注册过了")
        return username

    def clean_captcha(self):
        email = self.cleaned_data.get('email')
        captcha = self.cleaned_data.get('captcha')
        captcha_ = cache.get(email)
        if captcha != captcha_:
            raise forms.ValidationError("验证码错误")
    def clean_password_confirm(self):
        password = self.cleaned_data.get('password')
        password_confirm = self.cleaned_data.get('password_confirm')

        if password != password_confirm:
            raise forms.ValidationError("两次密码不一致")

        return password_confirm

class LoginForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(max_length=20, min_length=6, widget=forms.PasswordInput)